package edu.utn.tacs.grupouno.ui.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;

import edu.utn.tacs.grupouno.ui.client.dto.AnalisisDTO;
import edu.utn.tacs.grupouno.ui.client.dto.TurnoDTO;

public class AsignTurnoClickHandlerFactory implements ClickHandlerFactory<TurnoDTO> {
	
	private AnalisisDTO analisis;
	private DialogBox dialogBox;
	private Panel errorTarget;

	public AsignTurnoClickHandlerFactory(AnalisisDTO analisis, DialogBox dialogBox, Panel errorTarget) {
		this.analisis = analisis;
		this.dialogBox = dialogBox;
		this.errorTarget = errorTarget;
	}
	
	@Override
	public ClickHandler create(TurnoDTO turno) {
		return new TurnoSelectedClickHandler(dialogBox, analisis, turno);
	}

	private class TurnoSelectedClickHandler implements ClickHandler {
		private DialogBox dialogBox;
		private AnalisisDTO analisis;
		private TurnoDTO turno;
		public TurnoSelectedClickHandler(DialogBox box, AnalisisDTO analisis, TurnoDTO turno) {
			this.dialogBox = box;
			this.analisis = analisis;
			this.turno = turno;
		}
		@Override
		public void onClick(ClickEvent arg0) {
			errorTarget.clear();
			errorTarget.add(new Label("Guardando..."));
			
			TurnoUIServiceAsync service = GWT.create(TurnoUIService.class);
			service.asignarAnalisis(turno, analisis, new AsyncCallback<Void>() {
				@Override
				public void onSuccess(Void arg0) {
					dialogBox.hide();
				}
				@Override
				public void onFailure(Throwable arg0) {
					errorTarget.clear();
					errorTarget.add(new Label("Error. Intente nuevamente."));
				}
			});
		}
	}
}
